define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');


    var shopTable;
    var firstTime = true;
    var totalCount = 0;

    var dispatch = {
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "店铺配送管理") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.initShopTable();
            this.initValidator();
            this.initDatetimepicker();
            this.bindEvent();
            //默认取urlParam参数
            var shopId = CRM.getUrlParam("id");
            if (shopId) {
                $("#shop_id").val(shopId);
                this.doSearch();
            }
        },
        /**
         * 执行查询操作.
         */
        doSearch: function () {
            $("#J_Search").data('bootstrapValidator').validate();
            if ($("#J_Search").data('bootstrapValidator').isValid()) {
                $('#shop_table').DataTable().ajax.reload();
            }
        },
        /**
         * 初始化店铺的列表
         */
        initShopTable: function () {
            var self = this;
            shopTable = $("#shop_table").dataTable({
                "oLanguage": CRM.pageConfig,
                "sScrollX": "100%",   //表格的宽度
                "sScrollXInner": "100%",   //表格的内容宽度
                "bScrollCollapse": true,  //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
                "bPaginate": true,  //是否显示分页
                "bLengthChange": true,  //每页显示的记录数
                "bFilter": false, //搜索栏
                "bSort": false, //是否支持排序功能
                "bInfo": true, //显示表格信息
                "bAutoWidth": false,  //自适应宽度
                "bServerSide": true,//开启服务端处理
                "sAjaxSource": CRM.getOuterUrl('/shop/freight/CRM/searchFreight'),
                "fnInitComplete": function () {
                    this.fnAdjustColumnSizing(true);
                },
                "fnServerData": function (sSource, aoData, fnCallback) {
                    if (firstTime) {
                        firstTime = false;
                        return;
                    }
                    var _url = CRM.getOuterUrl('/shop/freight/CRM/searchFreight');
                    var deliveryAmountBegin = $("#dispatch_fee").val();
                    var deliveryAmountEnd = $("#dispatch_fee").val();
                    if ($("#dispatch_fee").val() == ">5") {
                        deliveryAmountBegin = 500;
                        deliveryAmountEnd = "";
                    }
                    var dataString = JSON.stringify({
                        "id": $("#shop_id").val(),
                        "deliveryAmountBegin": deliveryAmountBegin,
                        "deliveryAmountEnd": deliveryAmountEnd,
                        "serviceSwitch": $("#sdx_fee").val(),
                        "pageBegin": aoData[3].value / aoData[4].value + 1,
                        "pageSize": aoData[4].value,
                        "operator": $.cookie('_uk')
                    });
                    CRM.request({
                        "type": 'POST',
                        "url": _url,
                        "dataType": "json",
                        contentType: "application/json",
                        xhrFields: {
                            withCredentials: true
                        },
                        "data": dataString,
                        contentType: "application/json",
                        "success": function (req) {
                            if (req.responseCode && req.status) {
                                var resultData = CRM.getDataTabelDtaObject();
                                if (req.entry) {
                                    resultData.iTotalDisplayRecords = req.entry.num;
                                    resultData.iTotalRecords = req.entry.num;
                                    for (var length in req.entry.list) {
                                        resultData.aaData.push([
                                            req.entry.list[length].shopId,
                                            CRM.htmlEncode(req.entry.list[length].shopName),
                                            CRM.htmlEncode(req.entry.list[length].city),
                                            CRM.htmlEncode(req.entry.list[length].ownerName),
                                            CRM.htmlEncode(req.entry.list[length].xiaoerName),
                                            req.entry.list[length].leastSendAmount,
                                            // req.entry.list[length].freeFreightAmount,
                                            req.entry.list[length].deliveryAmount,
                                            {
                                                "id": req.entry.list[length].shopId
                                            }]);
                                    }
                                } else {
                                    CRM.showDialog(req.message);
                                }
                                fnCallback(resultData);
                            } else {
                                CRM.showDialog(req.message);
                            }
                        },
                        error: function (e) {
                            //请求出错处理
                            $("#msg_dialog_content").text("获取店铺列表,请求服务异常！");
                            $('#msg_dialog').modal('show');
                        }
                    });
                },
                "aaSorting": [[1, "asc"]],  //给列表排序 ，第一个参数表示数组 (由0开始)。1 表示Browser列。第二个参数为 desc或是asc
                "aoColumns": [
                    {
                        "sTitle": "店铺ID",
                        "bSortable": true
                    },
                    {
                        "sTitle": "店铺名称",
                        "bSortable": true
                    },
                    {
                        "sTitle": "所属城市",
                        "bSortable": true
                    },
                    {
                        "sTitle": "店铺所有者",
                        "bSortable": true
                    },
                    {
                        "sTitle": "当前管理小二",
                        "bSortable": true
                    },
                    {
                        "sTitle": "起送价(元)",
                        "bSortable": true,
                        "mRender": function (data, type, row) {
                            return data / 100;
                        }
                    },
                    // {
                    //     "sTitle": "免配送金额(元)",
                    //     "bSortable": true,
                    //     "mRender": function (data, type, row) {
                    //         return data / 100;
                    //     }
                    // },
                    {
                        "sTitle": "配送费(元)",
                        "bSortable": true,
                        "mRender": function (data, type, row) {
                            return data / 100;
                        }
                    },
                    {
                        "sTitle": "操作",
                        "bSortable": false,
                        "mRender": function (data) {
                            var id = data.id
                            var html = '<button type="button" class="btn btn-info" onclick="javascript:openFee(\'' + id + '\')">设置配送费</button>';
                            return html;
                        }
                    }

                ], //列设置，表有几列，数组就有几项
                "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
                "sPaginationType": "full_numbers" //分页，一共两种样式，full_numbers和two_button(默认)

            });
        },
        /**
         * 打开费用配置界面
         * @param shopId
         */
        openFee: function (shopId) {
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl('/shop/freight/selectFreightByShopId'),
                "dataType": "json",
                contentType: "application/json",
                "data": JSON.stringify({
                    "shopId": shopId,
                    "operator": $.cookie('_uk')
                }),
                "success": function (req) {
                    if (req.status) {
                        if(!req.entry.tryLocation){
                            $(".normal").removeClass("hidden");
                        }else{
                            $(".normal").addClass("hidden");
                        }
                        $("#shopId").val(shopId);
                        $("#leastSendAmount").val(req.entry.leastSendAmount / 100);
                        $("#freeFreightAmount").val(req.entry.freeFreightAmount / 100);
                        $("#deliveryAmount").val(req.entry.deliveryAmount / 100);
                        $("#periodSwitch").val(req.entry.periodSwitch);
                        $("#deliveryPayType").val(req.entry.deliveryPayType);
                        $("#timePeriodBegin").val(req.entry.timePeriodBegin);
                        $("#timePeriodEnd").val(req.entry.timePeriodEnd);
                        $("#timePeriodAmount").val(req.entry.timePeriodAmount / 100);
                        if ($("#periodSwitch").val() == 0) {
                            $("#time_div").hide();
                            $("#timePeriodAmount_div").hide();
                        } else {
                            $("#time_div").show();
                            $("#timePeriodAmount_div").show();
                        }
                        if (req.entry.deliveryPayType == 0) {
                            $("#deliveryPayPercent_div").hide();
                            $("#deliveryPayDan_div").show();
                        } else {
                            $("#deliveryPayPercent_div").show();
                            $("#deliveryPayDan_div").hide();
                        }
                        $("#deliveryPayDan").val(req.entry.deliveryPayDan / 100);
                        $("#deliveryPayPercent").val(req.entry.deliveryPayPercent / 100);
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
            $('#fee_dialog').modal('show');
            $('#fee_dialog').on('shown.bs.modal', function (e) {
                $("#fee_form").data('bootstrapValidator').resetForm();
            });
        },
        /**
         * 保存费用修改
         */
        saveFee: function () {
            //$("#deliveryPayType").removeAttr("disabled");
            $("#fee_form").data('bootstrapValidator').resetForm();
            $("#fee_form").data('bootstrapValidator').validate();
            if ($("#fee_form").data('bootstrapValidator').isValid()) {
                var dataString, _data = {};
                $($("#fee_form").serializeArray()).each(function () {
                    _data[this.name] = this.value;
                });
                _data.deliveryPayType = "0"; //将收费方式固定为按单
                _data.operator = $.cookie('_uk');
                _data.shopId = $('#shopId').val();
                dataString = JSON.stringify(_data);
                CRM.request({
                    "type": 'POST',
                    "url": CRM.getOuterUrl('/shop/freight/addOrUpdateShopFreight'),
                    "dataType": "json",
                    contentType: "application/json",
                    "data": dataString,
                    "success": function (req) {
                        if (req.status) {
                            $('#hongbao-detail-modal').modal('hide');
                            CRM.showDialog("设置成功！");
                        } else {
                            CRM.showDialog(req.message);
                        }
                    }
                });
            }

        },
        /**
         * 表单验证初始化
         */
        initValidator: function () {
            $('#J_Search').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    shop_id: {
                        message: 'error',
                        validators: {
                            regexp: {
                                regexp: /^[0-9]+$/,
                                message: '请输入数字'
                            }
                        }
                    }
                }
            });
            $('#fee_form').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {}
            });

        },
        /**
         * 根据用户ID获取用户信息
         * @param usserId
         */
        getUserById: function (usserId) {
            var returnObject;
            $.ajax({
                "type": 'GET',
                "url": CRM.getOuterUrl('/member/getUserbyUserId.do?userId=' + usserId),
                "dataType": "json",
                async: false, //请求是否异步，默认为异步，这也是ajax重要特性
                contentType: "application/json",
                xhrFields: {
                    withCredentials: true
                },
                contentType: "application/json",
                "success": function (req) {
                    if (req.responseCode == 0 && req.status) {
                        if (req.entry) {
                            $("#userMobile").val(req.entry.mobile);
                            returnObject = req.entry;
                        }
                    } else {
                        $("#msg_dialog_content").text(req.message);
                        $('#msg_dialog').modal('show');
                    }
                },
                error: function (e) {
                    //请求出错处理
                    $("#msg_dialog_content").text("根据用户ID获取用户信息,请求服务异常！");
                    $('#msg_dialog').modal('show');
                }
            });
            return returnObject;
        },
        /**
         * 初始化日期控件
         */
        initDatetimepicker: function () {
            $(".form_time").datetimepicker({
                language: 'zh-CN',
                weekStart: 1,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 1,
                minView: 0,
                maxView: 1,
                forceParse: 0
            });
            $('.form_date').datetimepicker({
                language: 'zh-CN',
                weekStart: 1,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                minView: 2,
                forceParse: 0
            });
        },
        bindEvent: function () {
            var self = this;
            $("#search_btn").on('click', function () {
                self.doSearch();
            });
            $("#deliveryPayType").on('change', function () {
                if ($("#deliveryPayType").val() == 0) {
                    $("#deliveryPayPercent_div").hide();
                    $("#deliveryPayDan_div").show();
                } else {
                    $("#deliveryPayPercent_div").show();
                    $("#deliveryPayDan_div").hide();
                }
            });
            $("#periodSwitch").on('change', function () {
                if ($("#periodSwitch").val() == 0) {
                    $("#time_div").hide();
                    $("#timePeriodAmount_div").hide();
                } else {
                    $("#time_div").show();
                    $("#timePeriodAmount_div").show();
                }
            });
        }
    };

    window.doSearch = $.proxy(dispatch.doSearch, dispatch);
    window.openFee = $.proxy(dispatch.openFee, dispatch);
    window.saveFee = $.proxy(dispatch.saveFee, dispatch);

    dispatch.init();
});